﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using spUtils;
using spMapping;
using spData.Common;

namespace demo.Controls
{
    public partial class AssessmentExt : TaskControl
    {
        #region Property
        public event EventHandler Send;
        public event EventHandler SaveAsDraft;
        public event EventHandler Aborted;
        bool isTransOption = false;        
        private List<t_Option> option = new List<t_Option>();
        public List<t_Option> Option
        {
            get
            {
                isTransOption = true; 
                return option;
            }
        }
        public string LegendName { get { return TaskAPI.IsInitiate ? "其他说明" : "审批/审核"; } }
        public string BackToSteps { get { return ViewState["BackToSteps"] == null ? "" : (string)ViewState["BackToSteps"]; } set { ViewState["BackToSteps"] = value; } }
        public bool IsConferWithBack { get { return ViewState["IsConferWithBack"] == null ? false : (bool)ViewState["IsConferWithBack"]; } set { ViewState["IsConferWithBack"] = value; } }
        public bool IsForwardWithBack { get { return ViewState["IsForwardWithBack"] == null ? false : (bool)ViewState["IsForwardWithBack"]; } set { ViewState["IsForwardWithBack"] = value; } }
        public bool IsReturned { get { return ViewState["IsReturned"] == null ? false : (bool)ViewState["IsReturned"]; } set { ViewState["IsReturned"] = value; } }
        private bool IsApprove { get { return TaskAPI.IsBeginStep || RadOpition.SelectedValue == "1"; } }
        private bool IsReturn { get { return RadOpition.SelectedValue == "2"; } }
        private bool IsConferTo { get { return P_ConferTo.Visible && !string.IsNullOrEmpty(ConferTo.Attributes["UserName"]); } }
        private bool AllowPrint { get; set; }
        public string EndTooltip { get { return ViewState["EndTooltip"] == null ? "" : (string)ViewState["EndTooltip"]; } set { ViewState["EndTooltip"] = value; } }
        public string EndTooltipText { get { return ViewState["EndTooltipText"] == null ? "" : (string)ViewState["EndTooltipText"]; } set { ViewState["EndTooltipText"] = value; } }
        public bool AllowAbort { get { return ViewState["AllowAbort"] == null ? true : (bool)ViewState["AllowAbort"]; } set { ViewState["AllowAbort"] = value; } }
        public bool IsCancelEvent = false;

        public string INFO { get { return ViewState["INFO"] == null ? "" : ViewState["INFO"].ToString(); } set { ViewState["INFO"] = value; } }
        #endregion

        #region Event Page
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!Page.IsPostBack)
            //{
            //    #region 是否允许“直接办结”
            //    if (TaskAPI.IsInitiate)
            //    {
            //        string s = USER.UserName.Contains("/") ? USER.UserName.Split('/')[1] : USER.UserName;
            //        TaskAPI.IsDirectComplete = (t_DirectComplete.process == Process & t_DirectComplete.userName == s
            //                                  & t_DirectComplete.status == 1 & t_DirectComplete.dateUntil>=System.DateTime.Now.ToString("yyyy-MM-dd")).Count<t_DirectComplete>() > 0;
            //    }
            //    #endregion

            //    #region 审批历史,初始化“退回至”列表
            //    if (!TaskAPI.IsInitiate)
            //    {
            //        //判断是否为被“加签”功能
            //        if (TaskAPI.AssignedToUserName != "SYSTEMUSER" && TaskAPI.UserName.ToLower() != USER.UserName.ToLower() && TaskAPI.AssignedToUserName.ToLower() != USER.UserName.ToLower())
            //        {
            //            IList<t_ConferTo> confs = (t_ConferTo.taskID == TaskID & t_ConferTo.assignedToUserName == USER.UserName & t_ConferTo.status == 1).List<t_ConferTo>(ORM.Context2);
            //            foreach(t_ConferTo conf in confs)
            //            {
            //                if(!IsConferWithBack && conf.Category.ToUpper() == "CONFERTO")
            //                {
            //                    IsConferWithBack = true;
            //                }

            //                if (!IsConferWithBack && conf.Category.ToUpper() == "FORWARD")
            //                {
            //                    IsForwardWithBack = true;
            //                }
            //            }
            //            TaskAPI.IsConferWithBack = IsConferWithBack;
            //        }else
            //        {
            //            //如果是被加签且意见尚未返回的情况，拒绝提交
            //            int confCount = (t_ConferTo.taskID == TaskID & t_ConferTo.status == 1).Count<t_ConferTo>(ORM.Context2);
            //            if (confCount > 0)
            //            {
            //                INFO = string.Format("<span style='color:blue;'>加签仍有<span style='color:red;font-weight:bold;'>{0}</span>人尚未发表意见，拒绝提交!</span>", confCount);    
            //            }
            //        }

            //        string tmp = "";
            //        IList<t_Assessment> asss = ((t_Assessment.process == Process & t_Assessment.process != ""
            //                                  & t_Assessment.incident == Incident) | (t_Assessment.process == AddProcess & t_Assessment.incident == AddIncident & t_Assessment.process != "")).List<t_Assessment>(new Region(0, 1000), t_Assessment.time.Asc);
            //        foreach (t_Assessment ass in asss)
            //        {
            //            //判断是否为退回步骤
            //            if (ass.ReturnTo == Step && ass.Process == Process)
            //            {
            //                TaskAPI.IsReturned = true;
            //                IsReturned         = true;
            //                tmp               += ass.Step + "<+>";
            //            }

            //            if (BackTo.Items.FindByValue(ass.Step) == null && ass.Process == Process
            //             && ass.Step != "加签" && ass.Step != "转发")
            //            {
            //                BackTo.Items.Add(new ListItem(ass.Step, ass.Step));
            //            }
            //        }

            //        #region 在意见栏中显示流程状态
            //        t_Assessment asTmp = new t_Assessment();
            //        if (TaskAPI.IncidentStatus == 2)
            //        {
            //            asTmp.Step                      = "申请单状态";
            //            asTmp.AssignedToUserFullName    = "系统检测";
            //            asTmp.Time                      = TaskAPI.CompletedTime;
            //            asTmp.OpinionText               = !string.IsNullOrEmpty(EndTooltip) ? EndTooltip : "流转已完成";
            //            asTmp.Remark                    = !string.IsNullOrEmpty(EndTooltipText) ? EndTooltipText : "";
            //            asss.Add(asTmp);
            //        }
            //        else if (TaskAPI.IncidentStatus == 4)
            //        {
            //            asTmp.Step                      = "申请单状态";
            //            asTmp.AssignedToUserFullName    = "系统检测";
            //            asTmp.Time                      = TaskAPI.CompletedTime;
            //            asTmp.OpinionText               = "已撤单";
            //            asss.Add(asTmp);
            //        }
            //        #endregion

            //        //保存被退回步骤名称
            //        BackToSteps = tmp;

            //        //缩写列表
            //        AssList.Visible = true;
            //        AssList.DataSource = asss;
            //        AssList.DataBind();
            //    }
            //    #endregion

            //    #region 审批项初始化
            //    bool bcwb = TaskAPI.IsBeginStep && !TaskAPI.IsInitiate && IsConferWithBack;
            //    if ((!isTransOption && !TaskAPI.IsBeginStep) || bcwb || IsForwardWithBack)
            //    {
            //        option.Add(new t_Option("同意", "1", true));
            //        option.Add(new t_Option("不同意", "3"));
            //        option.Add(new t_Option("退回", "2"));

            //        if (bcwb)
            //        {
            //            SetVisible(false, BackTo_L, BackTo);
            //        }
            //    }

            //    if (option.Count > 0)
            //    {
            //        int Selected = 0;
            //        RadOpition.Items.Clear();
            //        for (int i = 0; i < option.Count; i++)
            //        {
            //            RadOpition.Items.Add(new ListItem(option[i].RadName, option[i].RadValue));
            //            if (option[i].IsDefault)
            //            {
            //                Selected = i;
            //            }
            //        }

            //        RadOpition.Width = option.Count * 70;
            //        RadOpition.Items[Selected].Selected = true;
            //    }
            //    #endregion

            //    #region 禁/启用, 显示/不显示
            //    bool isPrint = false;
            //    bool isFoward = false;
            //    IList<t_Print> prints = (t_Print.process == Process & t_Print.step == Step).List<t_Print>();
            //    foreach(t_Print print in prints)
            //    {
            //        if(!isPrint && print.Category.ToUpper() == "PRINT")
            //        {
            //            isPrint = true;
            //        }

            //        if (!isFoward && print.Category.ToUpper() == "FORWARD")
            //        {
            //            isFoward = true;
            //        }
            //    }
            //    isFoward = !TaskAPI.IsInitiate && isFoward && !TaskAPI.IsAllowSubmit;

            //    bool flg = (TaskAPI.UserName.ToLower() == USER.UserName.ToLower()
            //             || TaskAPI.AssignedToUserName.ToLower() == USER.UserName.ToLower()
            //             || TaskAPI.AssignedToUserName == "SYSTEMUSER") && string.IsNullOrEmpty(INFO);

            //    SetEnable(TaskAPI.IsAllowSubmit || (isFoward && !IsForwardWithBack), ConferTo);
            //    SetEnable(TaskAPI.IsAllowSubmit || IsForwardWithBack, RadOpition, BackTo_L, BackTo);
            //    SetEnable(TaskAPI.IsBeginStep || (!TaskAPI.IsBeginStep && TaskAPI.IsAllowSubmit), Remark);

            //    SetVisible(!TaskAPI.IsInitiate && isPrint, BtnPrint);
            //    SetVisible(isFoward && !IsForwardWithBack, BtnForward);
            //    SetVisible(TaskAPI.IsInitiate || (TaskAPI.IsAllowSubmit && (flg || IsConferWithBack))
            //            || IsForwardWithBack, BtnSend);
            //    SetVisible(TaskAPI.IsInitiate, BtnSaveAsDraft);
            //    SetVisible((!TaskAPI.IsInitiate && TaskAPI.IsBeginStep && TaskAPI.IncidentStatus > 0 && TaskAPI.AssignedToUserName.ToLower() == USER.UserName.ToLower()
            //                                   && TaskAPI.IncidentStatus != 2 && TaskAPI.IncidentStatus != 4 && !IsConferWithBack && !IsForwardWithBack) && AllowAbort, BtnAbort);
            //    SetVisible(!TaskAPI.IsInitiate, BtnClose);
            //    SetVisible((!TaskAPI.IsBeginStep && flg && TaskAPI.IsAllowSubmit)
            //            || (TaskAPI.IsBeginStep && !TaskAPI.IsInitiate && TaskAPI.IsAllowSubmit && !IsConferWithBack)
            //            || isFoward && !IsForwardWithBack, P_ConferTo);
            //    TableApprove.Visible = (!TaskAPI.IsBeginStep && option.Count > 0 && (flg || IsConferWithBack))
            //                         || bcwb || IsForwardWithBack;
            //    SetVisible(!IsPrint, IsNotPrint);
            //    #endregion
            //}
        }
        #endregion

        #region Event Change Opition
        protected void RadOpition_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetVisible(false, BackTo_L, BackTo);
            Clear_Click(null, null);
            if (IsReturn)
            {
                BackTo_L.Text = "步骤:";
                SetVisible(true, BackTo_L, BackTo);                
            }
        }
        #endregion

        #region Event ConferTo
        protected void ConferTo_TextChanged(object sender, EventArgs e)
        {
            string user = "'" + ConferTo.Text.Replace(",", "','") + "-999'";//string.Format("'{0}'", ConferTo.Text.Replace("'", "''"));
            ConferTo.Attributes["UserName"] = user;
            string users = user;

            string sql = string.Format("select distinct UserShortName as UserName, UserFullName from Ult_UserJob where UserShortName <>'' and UserShortName in({0})", string.IsNullOrEmpty(users) ? "'-999'" : users);
            DataTable dt = ORM.Context2.ExecuteDataSet(new Command(sql)).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                string tmp = "";
                ConferTo.Text = "";
                foreach (DataRow dr in dt.Rows)
                {
                    ConferTo.Text += (string.IsNullOrEmpty(ConferTo.Text) ? "" : "; ") + dr["UserFullName"].ToString();
                    tmp += (string.IsNullOrEmpty(tmp) ? "" : ",") + "'" + dr["UserName"].ToString() + "'";
                }

                ConferTo.Attributes["UserName"] = tmp;
            }
            else
            {
                ConferTo.Text = "";
                ConferTo.Attributes["UserName"] = "";
            }
            BtnSend.Text = IsConferTo ? "加签" : "提交";
        }
        #endregion

        #region Event Forward
        protected void Forward_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(ConferTo.Text.Trim()))
            {
                Anthem.Manager.AddScriptForClientSideEval("JSInfomation('请选择对应的转发人!');");
                return;
            }

            //转发操作
            string[] forwards = ConferTo.Attributes["UserName"].Split(',');
            string domain =  USER.UserName.Contains("/") ? USER.UserName.Split('/')[0] + "/" : "";
            List<t_ConferTo> cts = new List<t_ConferTo>();
            List<t_ConferTo> cts2 = new List<t_ConferTo>();
            foreach (string forward in forwards)
            {
                t_ConferTo ct         = new t_ConferTo();
                ct.TaskID             = TaskID;
                ct.UserName           = USER.UserName;
                ct.Process            = Process;
                ct.Incident           = Incident;
                ct.Step               = Step;
                ct.AssignedToUserName = (forward.Contains("/") ? forward : string.Format("{0}{1}", domain, forward)).Replace("'", "");
                ct.Category           = "FORWARD";
                ct.Time               = System.DateTime.Now;
                ct.Status             = 1;
                cts.Add(ct);

                t_ConferTo ct2         = new t_ConferTo();
                ct2.TaskID              = TaskID;
                ct2.UserName = USER.UserName;
                ct2.Process = Process;
                ct2.Incident = Incident;
                ct2.Step = Step;
                ct2.AssignedToUserName = (forward.Contains("/") ? forward : string.Format("{0}{1}", domain, forward)).Replace("'", "");
                ct2.Category = "FORWARD";
                ct2.Time = System.DateTime.Now;
                ct2.Status = 1;
                cts2.Add(ct2);
            }
            ORM.Save(ORM.Context2, cts.ToArray());
            ORM.Save(cts2.ToArray());

            //加签
            t_Assessment confer = Assessment;
            confer.OpinionText  = "转发";
            confer.Remark       = string.Format("{0}[转发: {1}]", confer.Remark, ConferTo.Text);
            ORM.Save(confer);

            BtnForward.Visible = false;
            Anthem.Manager.AddScriptForClientSideEval(string.Format("JSInfomation('已转发至“{0}”!');", ConferTo.Text));
        }
        #endregion

        #region Event Print
        protected void Print_Click(object sender, EventArgs e)
        {
            Response.Redirect(ResolveUrl(string.Format("{0}?TaskID={1}&action=print", Request.AppRelativeCurrentExecutionFilePath, TaskID)), false);
        }
        #endregion

        #region Event Clear
        protected void Clear_Click(object sender, EventArgs e)
        {
            ConferTo.Text = "";
            ConferTo.Attributes["UserName"] = "";
            BtnSend.Text = IsConferTo ? "加签" : "提交";
        }
        #endregion

        #region Event Save As Draft, Send, Abort
        protected void Submit_Click(object sender, EventArgs e)
        {
            Anthem.Button tmp = sender as Anthem.Button;
            TaskAPI.IsConferWithBack = IsConferWithBack;
            TaskAPI.IsReturned = IsReturned;
            switch (tmp.ID)
            {
                #region 保存草稿
                case "BtnSaveAsDraft":
                    if(SaveAsDraft != null)
                    {
                        SaveAsDraft(this, e);
                    }
                    break;
                #endregion

                #region 提交
                case "BtnSend":

                    #region 加签--------------------
                    if (IsConferTo)
                    {
                        string[] forwards = ConferTo.Attributes["UserName"].Split(',');
                        string domain =  USER.UserName.Contains("/") ? USER.UserName.Split('/')[0] + "/" : "";
                        List<t_ConferTo> cts = new List<t_ConferTo>();
                        foreach (string forward in forwards)
                        {
                            t_ConferTo ct         = new t_ConferTo();
                            ct.TaskID             = TaskID;
                            ct.UserName           = USER.UserName;
                            ct.Process            = Process;
                            ct.Incident           = Incident;
                            ct.Step               = Step;
                            ct.AssignedToUserName = (forward.Contains("/") ? forward : string.Format("{0}{1}", domain, forward)).Replace("'", "");
                            ct.Category           = "CONFERTO";
                            ct.Time               = System.DateTime.Now;
                            ct.Status             = 1;
                            cts.Add(ct);
                        }
                        
                        ORM.Save(ORM.Context2, cts.ToArray());

                        //加签
                        t_Assessment confer = Assessment;
                        confer.OpinionText  = "加签";
                        confer.Remark       = string.Format("{0}[加签: {1}]", confer.Remark, ConferTo.Text);
                        ORM.Save(confer);

                        BtnSend.Visible = false;
                        Anthem.Manager.AddScriptForClientSideEval(string.Format("JSInfomation('已加签至“{0}”!');", ConferTo.Text));
                        return;
                    }
                    #endregion
                    
                    #region 非加签------------------
                    //如果是第一个步骤加签的情况，执行意见写入
                    if (IsConferWithBack)
                    {
                        //如果是开始步骤加签的情况，在数据库里补充意见
                        if (TaskAPI.IsBeginStep)
                        {
                            t_Assessment back = Assessment;
                            ORM.Save(back);

                            //加签意见回复后，收回加签权限
                            (t_ConferTo.taskID == TaskID & t_ConferTo.assignedToUserName == USER.UserName & t_ConferTo.category == "CONFERTO").Edit<t_ConferTo>(ORM.Context2, o => { o.Status = 2; });

                            SetVisible(false, BtnSend);
                            Anthem.Manager.AddScriptForClientSideEval("JSInfomation('提交成功!');window.close();");
                        }
                        //执行“提交”事件
                        else
                        {
                            if (Send != null)
                            {
                                Send(this, e);
                            }

                            //加签意见回复后，收回加签权限
                            if (!IsCancelEvent)
                            {
                                (t_ConferTo.taskID == TaskID & t_ConferTo.assignedToUserName == USER.UserName).Edit<t_ConferTo>(ORM.Context2, o => { o.Status = 2; });
                            }
                        }
                    }
                    else if (IsForwardWithBack)
                    {
                        t_Assessment forward = Assessment;
                        ORM.Save(forward);

                        //加签意见回复后，收回转发权限
                        (t_ConferTo.taskID == TaskID & t_ConferTo.assignedToUserName == USER.UserName & t_ConferTo.category == "FORWARD").Edit<t_ConferTo>(ORM.Context2, o => { o.Status = 2; });

                        SetVisible(false, BtnSend);
                        Anthem.Manager.AddScriptForClientSideEval("JSInfomation('提交成功!');window.close();");
                    }
                    //如果是被“加签”环节，不执行“返回”及“退回”功能
                    else
                    {
                        //“退回”后再“返回”
                        if (IsApprove && TaskAPI.IsReturned)
                        {
                            TaskAPI.GoToStep = BackToSteps;
                        }

                        //“退回”
                        if (IsReturn)
                        {
                            TaskAPI.GoToStep = BackTo.SelectedValue;
                        }

                        //如果加签人提前提交表单，收回“被加签”权限
                        if (!IsConferTo)
                        {
                            (t_ConferTo.taskID == TaskAPI.TaskID & t_ConferTo.status == 1).Edit<t_ConferTo>(ORM.Context2, o => { o.Status = 3; });
                        }

                        //执行“提交”事件
                        if (Send != null)
                        {
                            Send(this, e);
                        }
                    }
                    break;
                    #endregion
                    
                #endregion

                #region 撤单
                case "BtnAbort":
                    //意见栏里增加一行
                    t_Assessment ass    = Assessment;
                    ass.Opinion         = "Abort";
                    ass.OpinionText     = "撤单";
                    ORM.Save(ass);
                    BtnAbort.Visible    = !TaskAPI.AbortIncident();

                    //事件处理
                    if (Aborted != null)
                    {
                        Aborted(this, e);
                    }

                    //提示取消成功
                    if (!BtnAbort.Visible)
                    {
                        BtnSend.Visible = false;
                        Anthem.Manager.AddScriptForClientSideEval("JSInfomation('撤单成功!');");
                    }
                    break;
                #endregion
            }
        }        

        public void Refresh()
        {
            SetEnable(TaskAPI.IsAllowSubmit, RadOpition, BackTo, Remark);
            SetVisible(TaskAPI.IsAllowSubmit, BtnSend);
            SetVisible(TaskAPI.IsInitiate && TaskAPI.IsAllowSubmit, BtnSaveAsDraft);
        }
        #endregion

        #region Method Assessment
        public t_Assessment Assessment
        {
            get
            {
                //TaskAPI.IsReturned = IsReturned;
                t_Assessment ass   = new t_Assessment();
                ass.Process      = Process;
                ass.Incident     = Incident;
                try
                {
                    ass.Step = IsConferWithBack ? "加签" : (IsForwardWithBack ? "转发" : Step);
                }
                catch (Exception)
                { }
                ass.UserName     = TaskAPI.IsInitiate || string.IsNullOrEmpty(TaskAPI.AssignedToUserName) ? USER.UserName : TaskAPI.AssignedToUserName;
                ass.UserFullName = TaskAPI.IsInitiate || string.IsNullOrEmpty(TaskAPI.AssignedToUserFullName) ? USER.UserFullName : TaskAPI.AssignedToUserFullName;
                ass.AssignedToUserName     = USER.UserName;
                ass.AssignedToUserFullName = USER.UserFullName;
                ass.Department   = USER.Department;
                ass.StartTime    = TaskAPI.StartTime == null || TaskAPI.StartTime < System.DateTime.Now.AddYears(-20) ? System.DateTime.Now : TaskAPI.StartTime;
                ass.Time         = System.DateTime.Now;
                ass.Opinion      = TaskAPI.IsDirectComplete ? "99" : (IsApprove && TaskAPI.IsReturned ? "2" : RadOpition.SelectedValue);
                ass.OpinionText  = (TaskAPI.IsBeginStep && !IsConferWithBack && !IsForwardWithBack) ? (TaskAPI.IsInitiate ? "提交" : "再次提交")
                                                                              : (RadOpition.SelectedItem == null ? "" : RadOpition.SelectedItem.Text);
                ass.Opinion2     = "";
                ass.OpinionText2 = IsApprove && TaskAPI.IsReturned ? "退回后重新返回" : "";
                ass.Status       = 1;
                ass.ReturnTo     = IsReturn ? BackTo.SelectedValue : "";
                foreach(ListItem li in RadOpition.Items)
                {
                    ass.Opinion2     += li.Value + "~";
                    ass.OpinionText2 += li.Text + "~";
                }
                ass.Remark = Remark.Text.Replace("\\n", "<+>").Replace("\n", "<br/>").Replace("<+>", "\\n");
                return ass;
            }
        }
        #endregion
    }
}
